/**
 * 权限中间件
 */

const { validTeacherRigths } = require('../services/teachers');

/**
 * 需要排除校验的路由
 */
const ignoreRoute = ['/teachers/updateMyPassword', '/menus/rightsList'];

/**
 * 权限中间件
 * @param {*} ctx 
 * @param {*} next 
 */
const rights = async (ctx, next) => {
    try {
        if (!/^(\/\w+\/\w+)/.test(ctx.url)) {
            return ctx.body = {
                code: 0,
                msg: '非法路径'
            }
        }
        if (!ctx.state.user) {
            await next();
            return;
        }
        if (ignoreRoute.includes(RegExp.$1) || RegExp.$1.startsWith('/dictionary/')) {
            await next();
            return;
        }
        const { id } = ctx.state.user;
        const result = await validTeacherRigths(id, RegExp.$1);
        if (result) {
            await next();
        } else {
            ctx.body = {
                code: 0,
                msg: '您没有权限访问此接口'
            }
        }
    } catch (error) {
        ctx.app.emit('error', error);
        ctx.body = {
            code: 0,
            msg: '权限校验失败，请稍后再试'
        }
    }
}

module.exports = rights;